package com.itbaizhan.controller;

import com.itbaizhan.common.CommonResult;
import com.itbaizhan.entity.User;
import com.itbaizhan.service.IUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.management.JMException;
import java.util.List;

/**
 * 用户控制器
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @DubboReference
    private IUserService iUserService;

    /**
     * 添加功能
     * @param user
     * @return
     */
    @PostMapping("/adduser")
    public String adduser(User user){
        // 添加用户
        CommonResult save = iUserService.save(user);
        // 判断是否添加成功
        if(save.getCode() == 200){
            return "redirect:/ok";
        }else {
            return "redirect:/error";
        }
    }


    /**
     * 查询用户
     * @return
     */
    @GetMapping("/showuser")
    public ModelAndView findByAll(){
        ModelAndView modelAndView = new ModelAndView();
        // 查询用户
        User user = new User();
        CommonResult result = iUserService.findByUser(user);
        modelAndView.addObject("users",result.getData());
        modelAndView.setViewName("showuser");
        return modelAndView;

    }

    /**
     * 跳转到更新页面
     * @param id 用户id
     * @return
     */
    @GetMapping("/toupdate")
    public ModelAndView  toupdate(Long id){
        ModelAndView modelAndView = new ModelAndView();
        // 根据用户id查询用户
        User user = new User();
        user.setId(id);
        CommonResult result = iUserService.findByUser(user);
        // 返回页面
        modelAndView.setViewName("update");
        // 判断是否查询成功
        if (result.getCode() == 200){
            List<User> data = (List<User>) result.getData();
            if (data != null && !data.isEmpty()){
                // 数据
                modelAndView.addObject("user",data.get(0));
            }
        }
        return modelAndView;

    }


    /**
     * 更新用户
     * @param user
     * @return
     */
    @PostMapping("/update")
    public String update(User user){
        // 1、更新用户
        CommonResult commonResult = iUserService.updateUser(user);
        // 2、判断
        if (commonResult.getCode() == 200){
            return "redirect:/ok";
        }else {
            return "redirect:/error";
        }

    }


    /**
     * 删除用户
     * @param id 用户id
     * @return
     */
    @GetMapping("/delete")
    public String delete(Long id){
        //1、删除用户
        CommonResult commonResult = iUserService.deleteUser(id);
        // 2、判断
        if (commonResult.getCode() == 200){
            return "redirect:/ok";
        }else {
            return "redirect:/error";
        }
    }

}
